package com.example.his.api.utils;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;

/**
 * @author huixh
 */
@Component
@Slf4j
public class MinioUtil {
    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.access-key}")
    private String accessKey;

    @Value("${minio.secret-key}")
    private String secretKey;

    @Value("${minio.bucket}")
    private String bucketName;

    private MinioClient minioClient;

    @PostConstruct
    public void init() {
        minioClient = new MinioClient.Builder().endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }

    // 检查文件是否为图片
    private boolean isImage(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return false;
        }
        String contentType = file.getContentType();
        return contentType != null && contentType.startsWith("image");
    }

    public void uploadImage(String path, MultipartFile file) {

        // 检查文件是否为图片
        if (!isImage(file)) {
            log.error("上传失败：文件类型不是图片");
            throw new IllegalArgumentException("只允许上传图片文件");
        }

        try {
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(path)
                    .stream(file.getInputStream(), file.getSize(), 5 * 1024 * 1024)
                    .contentType(file.getContentType())
                    .build());
            log.debug("上传图片成功path：{}", path);
        } catch (Exception e) {
            log.error("上传图片失败");
        }
    }
}
